<template>
  <div class="app-container">
    <indexMap :queryOpen="queryOpen" @showHideQueryDiv="showHideQueryDiv" @getMap="getMap" @getMapData="getMapData" />
    <!--查询面板-->
    <el-card v-if="showHideQueryDivBool" class="new-queryDiv">
      <div class="new-queryDiv-inner">
        <el-form :model="queryParams" label-position="right" label-width="82px">
          <el-form-item label="选择版本">
            <el-input v-model="queryParams.versionCode" placeholder="请选择版本" :suffix-icon="MoreFilled" readonly
              @click="selectVersionCode" clearable />
          </el-form-item>
          <el-form-item label="省" prop="province">
            <el-input v-model="queryParams.province" placeholder="" readonly />
          </el-form-item>
          <el-form-item label="市" prop="city">
            <el-input v-model="queryParams.city" placeholder="" readonly />
          </el-form-item>
          <el-form-item label="区/县" prop="county">
            <el-input v-model="queryParams.county" placeholder="" readonly />
          </el-form-item>
          <!-- <el-form-item label="数据类型">
              <el-select v-model="queryParams.dataType" placeholder="请选择" clearable value-key="name">
                <el-option v-for="item in dataTypeInfoArray" :key="item.code" :label="item.name" :value="item.code">
                </el-option>
              </el-select>
            </el-form-item> -->
        </el-form>
        <el-row justify="space-around">
          <el-button @click="queryClick" type="primary">查询图层</el-button>
          <el-button @click="queryTableClick" type="primary">查询列表</el-button>
          <el-button plain @click="closeSelect">关闭</el-button>
        </el-row>
      </div>
    </el-card>
    <el-dialog title="选择版本" v-model="openLeader" width="900px" append-to-body @close="closeVersicode">
      <p></p>
      <el-form ref="selectRef" :model="pageSize">
        <el-row style="margin: 20px 0;">
          <el-col :span="8">
            <el-form-item label="省" label-width="80px">
              <!-- <el-input v-model="pageSize.dataRangeProvince" placeholder="请选择省" clearable /> -->
              <el-select v-model="pageSize.dataRangeProvince" placeholder="请选择省" @change="chooseProvince" clearable
                value-key="name">
                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市" label-width="80px">
              <!-- <el-input v-model="pageSize.dataRangeCity" placeholder="请选择市" clearable /> -->
              <el-select v-model="pageSize.dataRangeCity" placeholder="请选择市" @change="chooseCity" clearable
                value-key="name">
                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区县" label-width="80px">
              <!-- <el-input v-model="pageSize.dataRangeArea" placeholder="请选择区县" clearable /> -->
              <el-select v-model="pageSize.dataRangeArea" placeholder="请选择区县" @change="chooseCounty" clearable
                value-key="name">
                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleQuery1" style="float: right;">查询</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table ref="selectMunchRef" :data="leaderList" stripe v-loading="versionLoading">
        <el-table-column label="单选" width="55px">
          <template #default="scope">
            <el-radio :label="scope.row.id" v-model="selectRadio"
              @click.native.stop.prevent="getCurrentRow(scope.row)">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column label="序号" align="center" width="55">
          <template #default="scope">
            <span>{{ (pageSize.page - 1) * pageSize.rows + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="版本号" align="center" prop="versionCode" />
        <el-table-column label="数据名称" align="center" prop="dataName" />
        <el-table-column label="数据范围" align="center" prop="dataRange" />
        <el-table-column label="数据类型" align="center" prop="dataType" />
        <el-table-column label="上传人" align="center" prop="uploadUser" />
        <el-table-column label="上传时间" align="center" prop="uploadTime" />
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="pageSize.page" v-model:limit="pageSize.rows"
        @pagination="selectVersionCode" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="querySelect" auto-insert-space>确定</el-button>
          <el-button plain @click="openLeader = false" auto-insert-space>取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--表格面板-->
    <Table v-if="completeRefreshData == true" :versionCode="queryParams.versionCode" :typeName="typeName"
      :typeCode="selectType" :showTable="detailTable" @closeTableDiv="closeDetailResultDiv"></Table>
    <!--数据图层组件-->
    <MapLayers :map="map" :dataTypeInfoArray="dataTypeInfoArray" :selectionData="versionGeomText" :layerInfoParams="layerInfoParams"
      @setSelectId="setSelectId">
    </MapLayers>
    <el-collapse-transition>
        <el-card v-if="tableShow" class="mapLayers-card">
          <el-row style="margin: 10px 0;">
            <el-button plain @click="tableShow = false">关闭</el-button>
          </el-row>
          <el-table :data="tableData" style="width: 100%" :height="height">
            <el-table-column v v-for="item in tableNameListTown" :key="item.name" :prop="item.name" :label="item.id"
                width="180" />
          </el-table>
        </el-card>
      </el-collapse-transition>
  </div>
</template>

<script setup name="economics">
import indexMap from '@/map/basicDataManage/economics/indexMap.vue'
import { getProvince, getChildArea } from "@/api/system/division";
import { listAdministrativeArea } from '@/api/basicDataManage/economics.js'
import { getGeomByCode } from '@/api/basicDataManage/kilometerGrid/index.js'
import { iServerHttp } from "@/map/projMap.js";
import { getUserId } from '@/utils/auth'
import { MoreFilled } from '@element-plus/icons-vue'
import { page } from '@/api/basicDataManage/kilometerGrid/index.js'
import MapLayers from '@/map/components/mapLayers/index.vue';
//表格面板
import Table from '../kilometerGrid/table.vue';
import { ref } from 'vue';
import { debug } from 'util';

const { proxy } = getCurrentInstance();
const data = reactive({
  queryParams: {
    versionCode: '',
    dataName: '',
    dataType: '',
    dataRangeCountry: '',
    dataRangeProvince: '',
    dataRangeCity: '',
    dataRangeArea: '',
    versionStartTime: '',
    versionEndTime: '',
    uploadStartTime: '',
    uploadEndTime: '',
  },
  form: {
    banben: '保存新版本',
    dataScope: '1',
    type: '1',
    dataFileId: [],
    versionCode: ''
  },
  queryParams1: {
    dataRangeProvince: '',
    dataRangeCity: '',
    dataRangeArea: '',
  },
  rules: {
    dataFrom: [{ required: true, message: "数据来源不能为空", trigger: "blur" }],
  },
  pageSize: {
    dataRangeProvince: '', //版本范围省id
    dataRangeCity: '', //版本范围市id
    dataRangeArea: '', //版本范围县区id
    page: 1,
    rows: 10,
  },
  layerInfoParams: {//查询图层信息参数（图层序号、图层名称、查询条件、是否显示）
    code: "",
    name: "",
    sqlText: '',
    show: false
  },
})
const { queryParams, form, rules, queryParams1, pageSize, layerInfoParams } = toRefs(data);
//数据类型
const dataTypeInfoArray = ref([
  { code: "1", name: "经济公里格网", table: "jc_gdp", url: iServerHttp() + "/iserver/services/map-datacenter/rest/maps/jc_gdp@datacenter", zIndex: 4, fieldId: "id" }
]);
const showHideQueryDivBool = ref(false)
const queryOpen = ref(false)
const provinceData = ref([])
const cityData = ref([])
const areaData = ref([])
const openLeader = ref(false)
const leaderList = ref([])
const completeRefreshData = ref(false)
const selectId = ref(null);//选中查看详情数据Id
const selectType = ref("");//选中查看详情数据类型
const selectDataList = ref([]);//选中查看详情数据Id的1条数据
const selectListId = ref('')
const detailTable = ref(false);//是否显示表格面板
const total = ref(0)

const tableData = ref([])
const tableShow = ref(false)
const getMapData = (obj) => {
  tableData.value = obj
  tableShow.value = true
  closeDetailResultDiv()
}
const tableNameListTown = ref([
  { id: '编码', name: 'CODE' },{ id: '省编码', name: 'FXPC_XZQHB' },{ id: '省', name: 'PROVINCE' },{ id: '市编码', name: 'FXPC_XZ01' },
  { id: '市', name: 'CITY' },{ id: '县编码', name: 'FXPC_XZ02' }, { id: '区（县）', name: 'COUNTY' },{ id: '乡', name: 'TOWN' },
  { id: '数据版本', name: 'DATA_VERSION' },{ id: '唯一标识', name: 'FXPC_DATAI' }, { id: '调查对象编码', name: 'FXPC_DCDXB' },
  { id: '常住人口数', name: 'TZG7' }, { id: '创建人', name: 'CREATE_USER' },{ id: '创建日期', name: 'FXPC_CREAT' },
  { id: '更新日期', name: 'FXPC_UPDAT' },{ id: '修改人', name: 'UPDATE_USER' }
])
const height = ref(100)
watch(() => tableData.value, (val) => {
  height.value = 100
  if (val.length > 0 && val.length < 10) {
    height.value = val.length * 50 + 50
  }
  if (val.length >= 10) {
    height.value = 500
  }
}, { immediate: true, deep: true })
const showHideQueryDiv = (bool) => {//显示|隐藏查询面板
  queryOpen.value = false
  showHideQueryDivBool.value = bool;
  // if (bool) {
  //   showHideDivType.value = "showQueryDiv";
  // } else {
  //   showHideDivType.value = "";
  // }
  // //清空查询参数
  // clearQueryParams();
}

function closeSelect() {
  showHideQueryDivBool.value = false;
  queryOpen.value = true
}
/** 获取省列表 */
function getProvinceData() {
  getProvince().then((response) => {
    provinceData.value = response.data;
    completeRefreshData.value = true;//显示地图
  });
}
const cityId = ref('');
const countyId = ref('');
const provinceId = ref('');
//选择省
function chooseProvince(value) {
  let id = ''
  cityData.value = [];
  areaData.value = [];
  if (value == "全国") {
    form.value.dataRangeProvince = null;
  } else {
    if (showHideQueryDivBool.value) {//查询面板
      pageSize.value.dataRangeCity = null;
      pageSize.value.dataRangeArea = null;
      pageSize.value.dataRangeProvince = value.name;
      cityId.value = ''
      countyId.value = ''
      provinceId.value = value.id
      id = value.id
    }
    getChildArea(id).then(response => {
      cityData.value = response.data;
    });
  }
}
//选择市
function chooseCity(value) {
  let id = ''
  if (showHideQueryDivBool.value) {//查询面板
    pageSize.value.dataRangeCity = value.name;
    pageSize.value.dataRangeArea = null;
    cityId.value = value.id
    countyId.value = ''
    id = value.id
  }
  areaData.value = [];
  getChildArea(id).then((response) => {
    areaData.value = response.data;
  });
}
//选择区县
function chooseCounty(value) {
  if (showHideQueryDivBool.value) {//查询面板
    pageSize.value.dataRangeArea = value.name;
    countyId.value = value.id
  }
}
// 根据数据级别重置版本范围
const chooseFormScope = (value) => {
  if (value == "1") {//国家级
    queryParams1.value.dataRangeProvince = "全国";
  } else {
    queryParams1.value.dataRangeProvince = "";
  }
  queryParams1.value.dataRangeCity = "";
  queryParams1.value.dataRangeArea = "";
  form.value.dataRangeProvince = null;
  form.value.dataRangeCity = null;
  form.value.dataRangeArea = null;
  proxy.$refs['ruleForm'].validateField(['dataRangeProvince']);
  cityData.value = [];
  areaData.value = [];
}
const chooseFormScope1 = (value) => {
  if (value == "1") {//国家级
    pageSize.value.dataRangeProvince = "全国";
  } else {
    pageSize.value.dataRangeProvince = "";
  }
  pageSize.value.dataRangeCity = "";
  pageSize.value.dataRangeArea = "";
  form.value.dataRangeProvince = null;
  form.value.dataRangeCity = null;
  form.value.dataRangeArea = null;
  proxy.$refs['selectRef'].validateField(['dataRangeProvince']);
  cityData.value = [];
  areaData.value = [];
}
function handleQuery1() {
  versionLoading.value = true
  let params = {
    dataRangeProvince: pageSize.value.dataRangeProvince == '全国' ? '' : provinceId.value,
    dataRangeCity: cityId.value,
    dataRangeArea: countyId.value,
    page: pageSize.value.page,
    rows: pageSize.value.rows
  }
  listAdministrativeArea(params).then(res => {
    leaderList.value = res.data.list
    total.value = res.data.total
    versionLoading.value = false
  }).catch(() => versionLoading.value = false)
}
const versionLoading = ref(false)
function selectVersionCode() {
  versionLoading.value = true
  openLeader.value = true
  listAdministrativeArea({ ...pageSize.value }).then(res => {
    leaderList.value = res.data.list
    total.value = res.data.total
    versionLoading.value = false
  }).catch(() => versionLoading.value = false)
}
const selectRadio = ref('')
const selectionData = ref([])
function getCurrentRow(row) {
  if (selectRadio.value) {
    if (selectRadio.value == row.id) {
      selectRadio.value = ''
      selectionData.value = {};// 取消勾选就把回传数据清除
      return
    }
  }
  selectRadio.value = row.id;
  selectionData.value = row;
}
function querySelect() {
  queryParams.value.city = selectionData.value.cityName;
  queryParams.value.county = selectionData.value.areaName;
  queryParams.value.province = selectionData.value.provinceName;
  queryParams.value.versionCode = selectionData.value.versionCode;
  openLeader.value = false;
}
const selectData = ref([])
//文件及图层查询
function queryClick() {
  //查询数据类型
  queryDataType.value = queryParams.value.dataType;
  let dataType = queryDataType.value;
  if (dataType == null) {
    dataType = "";
  }
  selectId.value = "";//清空选中ID
  selectData.value = [];
  //查询条件
  let sqlText = "";
  //省市县查询过滤
  let province = queryParams.value.province;
  let city = queryParams.value.city;
  let county = queryParams.value.county;
  if (province && province !== "") {
    if (city && city !== "") {
      if (county && county !== "") {
        sqlText = "province like '%" + province + "%' and city like '%" + city + "%' and county like '%" + county + "%' and data_version = '" + queryParams.value.versionCode + "'";
      } else {
        sqlText = "province like '%" + province + "%' and city like '%" + city + "%' and data_version = '" + queryParams.value.versionCode + "'";
      }
    } else {
      sqlText = "province like '%" + province + "%' and data_version = '" + queryParams.value.versionCode + "'";
    }
  }
  //图层查询参数
  layerInfoParams.value = {//查询图层信息参数（图层序号、图层名称、查询条件、是否显示）
    code: '1',
    name: '经济公里格网',
    sqlText: sqlText,
    show: true,
  };
}
//获取数据类型序号
function getDataTypeIndex(type) {
  let code = null;
  let dataTypeArr = dataTypeInfoArray.value;
  for (let i = 0; i < dataTypeArr.length; i++) {
    if (dataTypeArr[i].code == type) {
      code = dataTypeArr[i].code;
      break;
    }
  }

  return code;
}
//设置选择数据ID
const setSelectId = (obj) => {
  if (obj) {
    selectDataList.value = [obj];
    let id = obj.selectListId;
    let dataType = obj.selectType;
    handleDetil(id, dataType);
  }
}
//根据id查询数据
function handleDetil(id, dataType) {
  detailTable.value = false;//关闭表格面板
  nextTick(() => {
    selectListId.value = id;//选中查看详情数据Id
    selectType.value = dataType;//选中查看详情数据类型
    detailTable.value = true;//打开表格面板
  });
}
//地图对象
const map = ref(null);
const getMap = (obj) => {
  map.value = obj;
}
//关闭表格面板
function closeDetailResultDiv() {
  detailTable.value = false;//关闭表格面板
}
const queryDataType = ref("");//查询数据类型
const typeName = ref('')
//查询列表数据
function queryTableClick() {
  typeName.value = '经济'
  //查询数据类型
  queryDataType.value = queryParams.value.dataType;
  let dataType = queryDataType.value;
  if (dataType == null) {
    dataType = "";
  }
  // if (dataType === "") {
  //   alertMsg("请选择数据类型!");
  //   return;
  // }
  if (queryParams.value.versionCode === "") {
    alertMsg("请选择数据版本!");
    return;
  }
  selectListId.value = "";//清空Id
  selectDataList.value = [];
  selectType.value = queryParams.value.dataType;//数据类型
  detailTable.value = true;//打开表格面板
}
//警告消息
function alertMsg(msg) {
  proxy.$modal.msgWarning(msg);
}
function closeVersicode() {
  pageSize.value.dataRangeCountry = ''
  pageSize.value.dataRangeProvince = ''
  pageSize.value.dataRangeCity = ''
  pageSize.value.dataRangeArea = ''
}
const versionGeomText = ref('')
watch(() => queryParams.value.versionCode, (val) => {
  if(val != '') {
    getGeomByCode({provinceId: selectionData.value.dataRangeProvince,cityId: selectionData.value.dataRangeCity,
    countyId: selectionData.value.dataRangeArea}).then(res => {
      versionGeomText.value = res
    })
  }else{
    versionGeomText.value = ''
  }
}, {immediate: true, deep: true})
onMounted(() => {
  getProvinceData();
});
</script>

<style lang="scss" scoped>
//查询面板
.new-queryDiv {
  position: absolute;
  top: 16px;
  left: 100px;
}

.new-queryDiv-inner {
  padding: 10px 0 0;
}
.mapLayers-card {
  position: absolute;
  bottom: 0;
  left: 10px;
  right: 10px;
  z-index: 2;
}
</style>
